//package com.dong.service;
//
//import com.dong.beans.Zone1AlarmResult;
//import com.dong.component.AlarmHandler;
//import com.dong.mybatis.entity.Zone1;
//import com.dong.mybatis.entity.Zone2;
//import com.dong.mybatis.entity.Zone3;
//import com.dong.mybatis.mapper.Zone1AlarmRecordMapper;
//import com.dong.mybatis.service.impl.Zone1ServiceImpl;
//import com.dong.mybatis.service.impl.Zone2ServiceImpl;
//import com.dong.mybatis.service.impl.Zone3ServiceImpl;
//import com.fasterxml.jackson.databind.ObjectMapper;
//import jakarta.annotation.PostConstruct;
//import jakarta.annotation.PreDestroy;
//import jakarta.annotation.Resource;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.stereotype.Component;
//
//import java.io.*;
//import java.net.ServerSocket;
//import java.net.Socket;
//import java.util.HashMap;
//import java.util.List;
//import java.util.Map;
//import java.util.concurrent.ConcurrentHashMap;
//import java.util.stream.Collectors;
//
///**
// * TCP服务器组件
// * 负责在指定端口监听客户端连接，并处理消息交互
// */
//@Slf4j
//@Component
//public class tcpservice {
//    @Autowired
//    private Zone1ServiceImpl zone1Service;
//
//    @Autowired
//    private Zone2ServiceImpl zone2Service;
//
//    @Autowired
//    private Zone3ServiceImpl zone3Service;
//
//    @Resource
//    AlarmHandler alarmHandler;
//
//    @Resource
//    Zone1AlarmService zone1AlarmService;
//
//    @Autowired
//    private Zone1AlarmRecordMapper zone1AlarmRecordMapper;
//
//    // 服务器Socket对象，用于监听端口
//    private ServerSocket serverSocket;
//    // 服务器运行状态标识
//    private boolean isRunning = false;
//    // 存储客户端socket的映射表
//    private Map<String, Socket> clientSockets = new ConcurrentHashMap<>();
//
//    /**
//     * 启动TCP服务器
//     * @PostConstruct注解：在Spring容器初始化该Bean后自动执行
//     */
//    @PostConstruct
//    public void startServer() {
//        // 设置运行状态为true
//        isRunning = true;
//
//        // 启动新线程运行服务器（避免阻塞Spring Boot启动）
//        new Thread(() -> {
//            try {
//                // 创建ServerSocket并绑定8888端口
//                serverSocket = new ServerSocket(8888);
//                System.out.println("TCP服务器已启动，监听端口：8888");
//
//                // 循环接收客户端连接（服务器主循环）
//                while (isRunning) {
//                    // 阻塞等待客户端连接，连接成功后返回Socket对象
//                    Socket clientSocket = serverSocket.accept();
//                    String clientAddress = clientSocket.getInetAddress().getHostAddress();
//                    System.out.println("👍👍👍新客户端连接：" + clientAddress);
//
//                    // 将客户端socket存储起来
//                    clientSockets.put(clientAddress, clientSocket);
//
//                    // 启动新线程处理该客户端的消息（避免单个客户端阻塞服务器）
//                    handleClient(clientSocket, clientAddress);
//                }
//            } catch (IOException e) {
//                // 服务器正常关闭时的异常无需报错
//                if (!isRunning) {
//                    System.out.println("TCP服务器已正常关闭");
//                } else {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
//    }
//
//    /**
//     * 处理客户端消息
//     * @param socket 与客户端连接的Socket对象
//     * @param address 客户端地址
//     */
//    private void handleClient(Socket socket, String address) {
//        new Thread(() -> {
//            try (
//                    // 不使用缓冲的输入流
//                    InputStreamReader in = new InputStreamReader(socket.getInputStream(), "UTF-8");
//                    // 不使用缓冲的输出流
//                    OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream(), "UTF-8")
//            ) {
//                System.out.println("客户端地址：" + address);
//                char[] buffer = new char[1024];
//                int bytesRead;
//                while ((bytesRead = in.read(buffer)) != -1) {
//                    String message = new String(buffer, 0, bytesRead);
//                    log.info("接收到了消息👍TCP" + message);
//
//                    ObjectMapper objectMapper = new ObjectMapper();
//                    Zone1 zone1 = objectMapper.readValue(message, Zone1.class);
//
//                    switch (address) {
//                        case "192.168.1.103":
//                            log.info("接收到了zone1数据😘TCP" + zone1.toString());
//                            zone1Service.save(zone1);
//                            handleZoneData(zone1, "zone1", zone1Service);
//                            checkAndHandleAlarms(zone1);
//                            break;
//                        case "192.168.1.104":
//                            Zone2 zone2 = objectMapper.readValue(message, Zone2.class);
//                            log.info("接收到了zone2数据😘TCP" + zone2.toString());
//                            alarmHandler.handleZone1Data(zone1, "zone2");
//                            zone2Service.save(zone2);
//                            checkAndHandleAlarms(zone1);
//                            break;
//                        case "192.168.1.105":
//                            Zone3 zone3 = objectMapper.readValue(message, Zone3.class);
//                            log.info("接收到了zone3数据😘TCP" + zone3.toString());
//                            alarmHandler.handleZone1Data(zone1, "zone3");
//                            zone3Service.save(zone3);
//                            checkAndHandleAlarms(zone1);
//                            break;
//                        default:
//                            log.info("接收到了未知数据😘TCP" + message);
//                            break;
//                    }
//                }
//                System.out.println("客户端已断开连接");
//            } catch (IOException e) {
//                System.out.println("客户端连接异常断开：" + e.getMessage());
//            } finally {
//                // 从存储中移除已断开的客户端
//                clientSockets.remove(address);
//                try {
//                    socket.close();
//                } catch (IOException e) {
//                    log.error("关闭客户端socket时出错", e);
//                }
//            }
//        }).start();
//    }
//
//    /**
//     * 统一处理Zone1数据
//     */
//    private <T> void handleZoneData(T zone, String zoneType, Object service) {
//        log.info("接收到了{}数据😘TCP{}", zoneType, zone.toString());
//        alarmHandler.handleZone1Data((Zone1) zone, zoneType);
//        boolean saveResult = false;
//        if (zone instanceof Zone1) {
//            saveResult = zone1Service.save((Zone1) zone);
//        }
//        log.info(saveResult ? "保存{}成功" : "保存{}失败", zoneType);
//    }
//
//    /**
//     * 检查并处理报警
//     */
//    private void checkAndHandleAlarms(Zone1 zone1) {
//        Map<String, Double> paramValues = new HashMap<>();
//        paramValues.put("temp", zone1.getTemp());
//        paramValues.put("humi", zone1.getHumi());
//        paramValues.put("v", zone1.getV());
//
//        List<Zone1AlarmResult> alarmResults = zone1AlarmService.batchCheckThresholdAlarm(paramValues);
//        List<Zone1AlarmResult> alarmList = alarmResults.stream()
//                .filter(Zone1AlarmResult::getIsAlarm)
//                .collect(Collectors.toList());
//
//        if (!alarmList.isEmpty()) {
//            System.out.println("有" + alarmList.size() + "个参数触发报警：");
//            alarmList.forEach(result -> System.out.println(result.getAlarmMsg()));
//        }
//    }
//
//    /**
//     * 获取当前连接的客户端列表
//     * @return 客户端地址列表
//     */
//    public Map<String, Socket> getClientSockets() {
//        return clientSockets;
//    }
//
//    /**
//     * 向指定客户端发送消息
//     * @param clientAddress 客户端地址
//     * @param message 消息内容
//     */
//    public void sendMessageToClient(String clientAddress, String message) {
//        Socket socket = clientSockets.get(clientAddress);
//        if (socket != null && !socket.isClosed()) {
//            try {
//                OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream(), "UTF-8");
//                out.write(message + "\n");
//                out.flush();
//            } catch (IOException e) {
//                log.error("向客户端 {} 发送消息失败", clientAddress, e);
//            }
//        }
//    }
//
//    /**
//     * 关闭TCP服务器
//     * @PreDestroy注解：在Spring容器销毁该Bean时自动执行（应用关闭时）
//     */
//    @PreDestroy
//    public void stopServer() {
//        // 设置运行状态为false，退出主循环
//        isRunning = false;
//
//        // 关闭所有客户端连接
//        for (Map.Entry<String, Socket> entry : clientSockets.entrySet()) {
//            try {
//                entry.getValue().close();
//            } catch (IOException e) {
//                log.error("关闭客户端连接时出错: {}", entry.getKey(), e);
//            }
//        }
//        clientSockets.clear();
//
//        try {
//            // 关闭ServerSocket，释放端口资源
//            if (serverSocket != null) {
//                serverSocket.close();
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//}


package com.dong.service;

import com.dong.beans.Zone1AlarmResult;
import com.dong.component.AlarmHandler;
import com.dong.mybatis.entity.Zone1;
import com.dong.mybatis.entity.Zone2;
import com.dong.mybatis.entity.Zone3;
import com.dong.mybatis.mapper.Zone1AlarmRecordMapper;
import com.dong.mybatis.mapper.Zone1Mapper;
import com.dong.mybatis.mapper.Zone2Mapper;
import com.dong.mybatis.mapper.Zone3Mapper;
import com.dong.mybatis.service.impl.Zone1ServiceImpl;
import com.dong.mybatis.service.impl.Zone2ServiceImpl;
import com.dong.mybatis.service.impl.Zone3ServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.PreDestroy;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

/**
 * TCP服务器组件
 * 负责在指定端口监听客户端连接，并处理消息交互
 */
@Slf4j
@Component
public class tcpservice {
    @Autowired
    private Zone1ServiceImpl zone1Service;

    @Autowired
    private Zone2ServiceImpl zone2Service;

    @Autowired
    private Zone3ServiceImpl zone3Service;
    @Resource
    AlarmHandler alarmHandler;
    @Resource
    Zone1Mapper zone1Mapper ;
    @Resource
    Zone2Mapper zone2Mapper ;
    @Resource
    Zone3Mapper zone3Mapper ;
    @Resource
    Zone1AlarmService zone1AlarmService;
    @Autowired
    private Zone1AlarmRecordMapper zone1AlarmRecordMapper;
    // 服务器Socket对象，用于监听端口
    private ServerSocket serverSocket;
    // 服务器运行状态标识
    private boolean isRunning = false;
    public static Map<String, Socket> clientSockets = new ConcurrentHashMap<>();

    /**
     * 启动TCP服务器
     * @PostConstruct注解：在Spring容器初始化该Bean后自动执行
     */
    @PostConstruct
    public void startServer() {
        // 设置运行状态为true
        isRunning = true;

        // 启动新线程运行服务器（避免阻塞Spring Boot启动）
        new Thread(() -> {
            try {
                // 创建ServerSocket并绑定8888端口
                serverSocket = new ServerSocket(8888);
                System.out.println("TCP服务器已启动，监听端口：8888");
//                clientSockets.put(clientAddress, serverSocket);

                // 循环接收客户端连接（服务器主循环）
                while (isRunning) {
                    // 阻塞等待客户端连接，连接成功后返回Socket对象
                    Socket clientSocket = serverSocket.accept();
                    String clientAddress = clientSocket.getInetAddress().getHostAddress();
                    clientSockets.put(clientAddress, clientSocket);
                    System.out.println("新客户端连接：" + clientSocket.getInetAddress().getHostAddress());

                    // 启动新线程处理该客户端的消息（避免单个客户端阻塞服务器）
                    handleClient(clientSocket, clientSocket.getInetAddress().getHostAddress());
                }
            } catch (IOException e) {
                // 服务器正常关闭时的异常无需报错
                if (!isRunning) {
                    System.out.println("TCP服务器已正常关闭");
                } else {
                    e.printStackTrace();
                }
            }
        }).start();
    }
    /**
     * 处理客户端消息
     * @param socket 与客户端连接的Socket对象
     */
    private void handleClient(Socket socket,String address) {

        new Thread(() -> {
            try (
                    // 不使用缓冲的输入流
                    InputStreamReader in = new InputStreamReader(socket.getInputStream(), "UTF-8");
                    // 不使用缓冲的输出流
                    OutputStreamWriter out = new OutputStreamWriter(socket.getOutputStream(), "UTF-8")
            ) {
//                String address = clientSocket.getInetAddress().getHostAddress();
                System.out.println("客户端地址：" + address);
                char[] buffer = new char[1024];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    String message = new String(buffer, 0, bytesRead);
                    log.info("接收到了消息👍TCP" + message);
                    ObjectMapper objectMapper = new ObjectMapper();
                    Map<String, Double> paramValues = new HashMap<>();
                    Zone1 zone1 = new Zone1();
                    zone1 = objectMapper.readValue(message, Zone1.class);
                    switch ( address) {
                        case "192.168.1.103":
//                            Zone1 zone1 = new Zone1();
                            zone1 = objectMapper.readValue(message, Zone1.class);
                            alarmHandler.handleZone1Data(zone1,"zone1");
                            log.info("接收到了zone1数据😘TCP" + zone1.toString());
//                            zone1Mapper.insert(zone1);
                            boolean save1 = zone1Service.save(zone1);
                            log.info(save1 ? "保存Zone1成功" : "保存Zone1失败");
// 2. 批量判断
                            List<Zone1AlarmResult> alarmzone1Results = zone1AlarmService.batchCheckThresholdAlarm(paramValues);
                            break;
                        case "192.168.1.104":
                            log.info("到达了case2😁");
                            Zone2 zone2 = new Zone2();
//                           ObjectMapper objectMapper = new ObjectMapper();
                            zone2 = objectMapper.readValue(message, Zone2.class);
                            alarmHandler.handleZone1Data(zone1,"zone2");
                            log.info("接收到了zone2数据😘TCP" + zone2.toString());
//                            zone2Mapper.insert(zone2);
                            boolean save2 = zone2Service.save(zone2);
                            log.info(save2 ? "保存Zone2成功" : "保存Zone2失败");

// 2. 批量判断
                            List<Zone1AlarmResult> alarmzone1Results_2 = zone1AlarmService.batchCheckThresholdAlarm(paramValues);

// 3. 遍历结果（如筛选出报警的参数）
                            break;
                        case "192.168.1.105":
                            log.info("到达了case3😁");
                            Zone3 zone3 = new Zone3();
//                           ObjectMapper objectMapper = new ObjectMapper();
                            zone3 = objectMapper.readValue(message, Zone3.class);
                            alarmHandler.handleZone1Data(zone1,"zone3");
                            log.info("接收到了zone1数据😘TCP" + zone3.toString());
//                            zone3Mapper.insert(zone3);
                            boolean save3 = zone3Service.save(zone3);
                            log.info(save3 ? "保存Zone3成功" : "保存Zone3失败");
// 2. 批量判断
                            List<Zone1AlarmResult> alarmzone1Results_3 = zone1AlarmService.batchCheckThresholdAlarm(paramValues);
                            break;
                        default:
//                            Zone1 zone = new Zone1();
//
//                            zone1 = objectMapper.readValue(message, Zone1.class);
//                            log.info("接收到了zone1数据😘TCP" + zone.toString());
//                            zone1Mapper.insert(zone);
                            log.info("接收到了未知数据😘TCP" + message);
                            break;
                    }
                    // 可选：回复客户端
                    // out.write("服务器已接收：" + message);
                    // out.flush(); // 手动刷新
                }
                System.out.println("客户端已断开连接");
            } catch (IOException e) {
                System.out.println("客户端连接异常断开：" + e.getMessage());
            }
        }).start();
    }


    /**
     * 关闭TCP服务器
     * @PreDestroy注解：在Spring容器销毁该Bean时自动执行（应用关闭时）
     */
    @PreDestroy
    public void stopServer() {
        // 设置运行状态为false，退出主循环
        isRunning = false;
        try {
            // 关闭ServerSocket，释放端口资源
            if (serverSocket != null) {
                serverSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}